from flask import Blueprint, render_template, request, session, redirect, jsonify, url_for,flash
from .forms import CommentForm
from app.models import *
from ..exts import db
bp=Blueprint('blog',__name__,url_prefix='/')

@bp.route('/')
def index():
    # return '登录成功！欢迎来到Likt安全博客系统登录页面！！！'
    blogs=BlogModel.query.filter_by(status='published').order_by(BlogModel.create_time.desc()).all()
    return render_template('index.html',blogs=blogs)

@bp.route('/comment')
def comment():
    comments=CommentModel.query.order_by(CommentModel.create_time.desc()).all()
    return render_template('comment.html',comments=comments)

@bp.route('/categories')
def categories():
    categories=CategoriesModel.query.all()
    return render_template('categories.html',categories=categories)

@bp.route('/topics')
def topics():
    topics=TopicModel.query.all()
    return render_template('topics.html',topics=topics)

@bp.route('/pertopic/<int:topic_id><string:topic_name>')
def pertopic(topic_id,topic_name):
    topic=TopicModel.query.filter_by(id=topic_id).first()
    # blogs=topic.blogstop
    blogs= [b for b in topic.blogstop if b.status == 'published' and b.is_deleted == False]
    return render_template('pertopic.html',blogs=blogs,topic=topic)
@bp.route('/percategory/<int:category_id><string:category_name>')
def percategory(category_id,category_name):
    category=CategoriesModel.query.filter_by(id=category_id).first()
    blogs=category.blogscat
    blogs= [b for b in blogs if b.status == 'published' and b.is_deleted == False]
    return render_template('percategory.html',blogs=blogs,category=category)


@bp.route('/detail/<int:blog_id>')
def detail(blog_id):
    blog=BlogModel.query.filter_by(id=blog_id).first()
    return render_template('detail.html',blog=blog)

@bp.route('/postComment',methods=['GET','POST'])
def post_comment():
    if request.method=='GET':
        return render_template('comment.html')
    else:
        form=CommentForm(request.form)
        if form.validate():
            nickname=form.nickname.data
            content=form.content.data
            comment=CommentModel(nickname=nickname,content=content)
            db.session.add(comment)
            db.session.commit()
            flash("留言发布成功", "success")
            return redirect(url_for('blog.comment'))
        else:
            flash('表单验证失败','danger')
            return render_template('comment.html', form=form)


